<template>
  <div class="logReg-container">
    <el-form
      ref="logRegForms"
      :model="logRegForm"
      :rules="logRegRules"
      class="logReg-form"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">橙券后台管理系统</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="logRegForm.username"
          placeholder="用户名"
          name="username"
          type="text"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="logRegForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          @keyup.enter="handleLogin(logRegForms)"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <el-form-item prop="email" v-if="!isLogin">
        <span class="svg-container">
          <svg-icon icon-class="email" />
        </span>
        <el-input
          ref="email"
          v-model="logRegForm.email"
          placeholder="邮箱"
          name="email"
          type="text"
          @keyup.enter="handleReg(logRegForms)"
        />
      </el-form-item>
      <el-button
        :loading="loading"
        type="primary"
        size="large"
        style="width: 100%; margin-bottom: 30px"
        @click.prevent="handleSubmit(logRegForms)"
        >{{ isLogin ? '登录' : '注册' }}</el-button
      >
      <div class="tips">
        <!-- <span>账号：admin123</span>
        <span style="margin-right: 20px">密码：Wdd123456</span> -->
        <a class="reglink" @click.prevent="isLogin = false" v-if="isLogin">没有登陆点击注册?</a>
        <a class="reglink" @click.prevent="isLogin = true" v-else>已经注册点击登录</a>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { validUsername, validPassword, validEmail } from '@/utils/validate/login'
import { ref, reactive, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
//引入获取当前时间的函数
import { getTime } from '@/utils/time'
//引入用户相关的小仓库
import useUserStore from '@/stores/modules/user'
let useStore = useUserStore()
defineOptions({ name: 'Login' })
const validateUsername = (rule, value, callback) => {
  if (!validUsername(value)) {
    callback(new Error('用户名必须为 数字+字母 6-8位'))
  } else {
    callback()
  }
}
const validatePassword = (rule, value, callback) => {
  if (!validPassword(value)) {
    callback(new Error('密码必须为 数字+密码(大小写) 8-12位'))
  } else {
    callback()
  }
}
const validateEmail = (rule, value, callback) => {
  if (!validEmail(value)) {
    callback(new Error('请输入合法邮箱地址'))
  } else {
    callback()
  }
}
// 是否是登陆操作
const isLogin = ref(true)
const loading = ref(false)
const password = ref('password')
const passwordType = ref('password')
const logRegForms = ref(null)
//获取路由器
let $router = useRouter()
//路由对象
let $route = useRoute()
// 跳转页面
const redirect = computed(() => {
  return isLogin.value && $route.query.redirect ? $route.query.redirect : '/'
})
// 请求地址
const apiPath = computed(() => {
  return isLogin.value ? 'userLogin' : 'userRegister'
})
// 提示语句
const elNotificationMessage = computed(() => {
  return isLogin.value ? '欢迎回来' : '欢迎注册橙劵后台管理系统'
})

// 表单
const logRegForm = reactive({
  username: 'admin123',
  password: 'Wdd123456',
  email: ''
})
// 检验规则
const logRegRules = reactive({
  username: [{ required: true, trigger: 'blur', validator: validateUsername }],
  password: [{ required: true, trigger: 'blur', validator: validatePassword }],
  email: [{ required: !isLogin.value, trigger: 'blur', validator: validateEmail }]
})
// 提交
const handleSubmit = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!')
      loading.value = true
      try {
        //保证请求成功
        await useStore[apiPath.value](logRegForm)
        $router.push({ path: redirect.value })
        // //成功提示信息
        setTimeout(() => {
          ElNotification({
            type: 'success',
            message: elNotificationMessage.value,
            title: `HI,${getTime()}好`
          })
        }, 1200)
        //成功加载效果也消失
        loading.value = false
      } catch (error) {
        //失败加载效果消息
        loading.value = false
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}
// 回车提交登录
const handleLogin = (formEl) => {
  if (!formEl && !isLogin.value) return
  handleSubmit(formEl)
}
// 回车提交注册
const handleReg = (formEl) => {
  if (!formEl && isLogin.value) return
  handleSubmit(formEl)
}

// 密码切换
const showPwd = () => {
  if (passwordType.value === 'password') {
    passwordType.value = ''
  } else {
    passwordType.value = 'password'
  }
  nextTick(() => {
    password.value.focus()
  })
}
</script>

<style lang="scss">
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .logReg-container .el-input input {
    color: $cursor;
  }
}

/* reset element-plus css */
.logReg-container {
  .el-form-item.is-error {
    .el-input__wrapper {
      background: none;
      box-shadow: none;
      display: block;
    }
  }
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    .el-input__wrapper {
      background: none;
      box-shadow: none;
      display: block;
    }
    input {
      background: transparent;
      border: 0px;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.reglink {
  color: #409eff;
  text-decoration: underline;
}
.logReg-container {
  min-height: 100vh;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .logReg-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
